import express from 'express'
import axios from 'axios';
import path from 'path'
import cookieParser from 'cookie-parser'
import session from 'express-session'


function log(...args: any[]) {
    console.log('[OAUTH DEMO]:', ...args);
}


const { client_secret } = process.env
log('client_secrect', client_secret)

const client_id = '0cfd6ea020f6d1ec304388f77026dd368acef37996162c9c259c60f528b03891'

// const redirect_uri = 'http://localhost:3000/login' // 地址正确，授权页， 列出即将授予的权限列表，可点击【同意授权】按钮 完成授权
const redirect_uri = 'http://localhost:3000/index.html'

const app = express()

app.use(express.static('public'));

app.use(express.json());


app.use(cookieParser('hello-my-secret'))
app.use(session({ name: 'EXPSID', secret: 'my-session-secret' }));


app.get('/hello', (req, res) => {
    req.session.visitCount = (req.session.visitCount || 0) + 1
    res.end('hello world   ' + req.session.visitCount);
})

app.get('/login', async (req, res) => {
    log('req.url:', req.url)
    log('req.query:', req.query)

    try {
        const authRes = await axios.post(`https://gitee.com/oauth/token`, {
            grant_type: 'authorization_code',
            code: req.query.code,
            redirect_uri: 'http://localhost:3000/login',
            client_id,
            client_secret,
            // redirect_uri, // redirect_uri 需要和获取code时传递一样的, 所以还是接收前端传入比较好
        })

        res.cookie('token', authRes.data.access_token);

        req.session.authData = authRes.data;

        // res.redirect('/index2.html')
        // log('authRes:', authRes);

        // res.send(JSON.stringify({ success: true, data: authRes.data }))

        res.sendFile(path.resolve(__dirname, '../public/redirect.html'));

    } catch (err: any) {
        // res.json({ success: false, msg: 'get token fail ' + err.message });
        res.send(JSON.stringify({ success: false, msg: 'get token fail ' + err.message }))

    }

})

app.post('/getToken', async (req, res) => {
    log(req.body, '<----req.body',);
    log(req.query, '<----req.query',);
    log(req.cookies, '<----req.cookies',);



    // POST https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}


    /*
    authRes.data =>  {
    access_token: '48d12ea059424a0f74c6f1eab0acdddd',
    token_type: 'bearer',
    expires_in: 86400,
    refresh_token: '1b1c488730359a9f9c22adc60c5e5e28023deddcce06a34739664ac0d1f2901f',
    scope: 'user_info pull_requests emails',
    created_at: 1698995767
  }
    */
    try {
        const authRes = await axios.post(`https://gitee.com/oauth/token`, {
            grant_type: 'authorization_code',
            code: req.body.code,
            redirect_uri: req.body.redirect_uri,
            client_id,
            client_secret,
            // redirect_uri, // redirect_uri 需要和获取code时传递一样的, 所以还是接收前端传入比较好
        })

        res.cookie('token', authRes.data.access_token);
        // log('authRes:', authRes);
        res.json({ success: true, data: authRes.data })
    } catch (err: any) {
        res.json({ success: false, msg: 'get token fail ' + err.message });

    }


})

app.post('/refreshTokenByBackend', (req, res) => {
    const { authData = {} } = req.session
    log('authData::', authData);

    const { refresh_token } = authData
    log('req.body=======>', req.body)

    // https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token={refresh_token}
    axios.post(`https://gitee.com/oauth/token`, {
        grant_type: 'refresh_token',
        redirect_uri: 'http://localhost:3000/login',
        refresh_token,
        client_id,
        client_secret
    })
        .then(refreshRes => {
            res.json({ success: true, data: refreshRes.data })
        })
        .catch((err: any) => {
            res.json({ success: false, msg: 'refresh token fail ' + err.message, reason: err?.config?.data });
            console.log('err.config.data ===>', err.config.data);
            console.log('err.response.data ===>', err.response.data);
        })
})

app.post('/refreshToken', (req, res) => {
    const { refresh_token } = req.body
    log('req.body=======>', req.body)

    // https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token={refresh_token}
    axios.post(`https://gitee.com/oauth/token`, {
        grant_type: 'refresh_token',
        redirect_uri: req.body.redirect_uri,
        refresh_token,
        client_id,
        client_secret
    })
        .then(refreshRes => {
            res.json({ success: true, data: refreshRes.data })
        })
        .catch((err: any) => {
            res.json({ success: false, msg: 'refresh token fail ' + err.message, reason: err?.config?.data });
            console.log('err:', err);
        })
})


const port = 3000
app.listen(port, () => console.log(`running at http://localhost:${port}`));

